﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
//using SerialPortHelperLib;
using System.Threading;
using System.Configuration;
using XChip_Common;
using XChipTool.Enties;
using BinAnalysisHelp;
using AdbService;

namespace XChipTool
{
    public partial class XChip_DNR : DevExpress.XtraEditors.XtraUserControl
    {

        public  SerialPort sPortTemp;
        private bool isRead = false;
        private KeyEventArgs keyEnter = new KeyEventArgs(Keys.Enter);//用来手动触发文本框下发配置
        private bool isWrite = false;
        List<string> listfiltration = new List<string> { "scale_sig", "slope", "offset" };
        private addressregisterManager aBll;
        private List<addressregister> XChipDnr;
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;
        // 使用服务定位器获取ADB服务
        private IAdbCommandService adbService = ServiceLocator.AdbCommandService;
        public XChip_DNR()
        {
            InitializeComponent();
        }
        public XChip_DNR(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            //sPortTemp = _sPortTemp;
            aBll = _aBll;
            XChipDnr = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "DNR" || c.Classify == "Common"));

            InitializeComponent();
        }

        private async Task<long> GetDNRRegister(string nameType)
        {
            if (XChipDnr.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
            {
                long var = await ReadRegisterAsync(XChipDnr.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address);
                return var;
            } 
            else 
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1; 
            }
        }
    
        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            isRead = true;
            WaitBefore.Start("读取中", "正在加载中", 10);
            // 记录开始时间和寄存器计数
            var startTime = DateTime.Now;
            int totalRegisterCount = 0;

            List<string> NameList = new List<string>();

            for (int i = 0; i < XChipDnr.Count; i++)
            {
                if (XChipDnr[i].NameType.Contains("Parn_En"))
                {
                    
                }
                var type = AppHelper.NameTypeToString(XChipDnr[i].NameType.ToLower());
                //加上单选框的_en
                if (XChipDnr[i].ControlType == "1")
                {
                    type = XChipDnr[i].NameType;
                }
                var col = this.Controls.Find(type, true);

                foreach (var item in col)
                {
                    if (NameList.Exists(c => c == (type)))
                    {
                        continue;
                    }
                    else
                    {

                        if (item is TextEdit)
                        {

                            var nList = XChipDnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            if (nList.Count == 0)
                            {
                                nList = XChipDnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            }
                            if (nList.Count == 1)
                            {
                                // 单个寄存器读取
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                            }
                            else if (item.Name == "Wt_Pedestal" || item.Name == "Cur_Still_Px_Wt" || item.Name == "Cur_Move_Px_Wt" || item.Name == "Max_Move_Px_Wt" || item.Name == ("Raw_Rbsl1"))
                            {
                                nList = XChipDnr.Where(c => c.NameType.ToLower() == (item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                                if (nList.Count() == 1)
                                {
                                    // 单个寄存器读取
                                    var address = nList[0].Address;
                                    totalRegisterCount++;
                                    await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                                }
                            }
                            else
                            {
                                // 多个寄存器组合读取
                                totalRegisterCount += nList.Count;
                                await ReadMultipleRegistersAndUpdateTextAsync(nList, item as TextEdit);
                            }
                        }
                        else if (item is CheckEdit)
                        {
                            var nList = XChipDnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                            if (nList.Count == 1)
                            {
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateCheckAsync(address, item as CheckEdit, nList[0].Bits, nList[0].Hex);
                            }
                        }


                    }
                }
                NameList.Add(type);
            }

            if (((await GetDNRRegister("Px_Wt_Man_en")& 0x4) == 0x4) && ((await GetDNRRegister("Px_Wt_Man3_en") & 0x8) == 0x8))
            {
                Px_Wt_Man_en.Checked = true;
            }
            else
            {
                Px_Wt_Man_en.Checked = false;

            }
            //bit1置0才是勾选
            if ((await GetDNRRegister("Parn_en") & 0x2) == 0x2)
            {
                Parn_en.Checked = false;
            }
            else
            {
                Parn_en.Checked = true;
            }
            isRead = false;
            WaitBefore.Close();

            #region 勾选框判断逻辑
           
            if (Parn_en.CheckState == CheckState.Checked)
            {
                ThreeDParnEnShowHide(true);
                RawGslAndRawRbslShowHide(false);
            }
            else
            {
                ThreeDParnEnShowHide(false);
                RawGslAndRawRbslShowHide(true);
            }

            if (Px_Wt_Man_en.CheckState == CheckState.Checked) //这个是勾选下发值
            {
               
                PxWtManEnShowHide(false);
                Move_Px_Wt_Cal_en.Enabled = true;
                Still_Px_Wt_Cal_en.Enabled = true;

                MovePxWtCalEnShowHide(Move_Px_Wt_Cal_en.Checked);
                StillPxWtCalEnShowHide(Still_Px_Wt_Cal_en.Checked);

            }
            else
            {
                PxWtManEnShowHide(true);
                Move_Px_Wt_Cal_en.Enabled = false;
                Still_Px_Wt_Cal_en.Enabled = false;
                MovePxWtCalEnShowHide(false);
                StillPxWtCalEnShowHide(false);
                Cur_Move_Px_Wt.Enabled = false;
                Cur_Still_Px_Wt.Enabled = false;

            }

            if (lap_enhancement_en.CheckState == CheckState.Checked)
            {
                lap_enhancement_Enable(true);
                if (soft_thr_en.CheckState == CheckState.Checked)
                {
                    soft_thr_Enable(true);
                    SetTxtSlopeMan_Enable(soft_thr_slope_man_en.Checked);
                    SetTxtOffsetMan_Enable(soft_thr_offset_man_en.Checked);
                    soft_thr_offset_man_en.Enabled = true;
                    soft_thr_slope_man_en.Enabled = true;
                    if (soft_thr_offset_man_en.Checked)
                    {
                        soft_thr_offset_man.Enabled = true;
                    }
                    if (soft_thr_slope_man_en.Checked)
                    {
                        soft_thr_slope_man.Enabled = true;
                    }
                }
                else
                {
                    soft_thr_Enable(false);
                    soft_thr_offset_man_en.Enabled = false;
                    soft_thr_slope_man_en.Enabled = false;
                    soft_thr_slope_man.Enabled = false;
                    soft_thr_offset_man.Enabled = false;
                }

            }
            else
            {
                lap_enhancement_Enable(false);
            }

            SetMotionPixel();
            SetStillPixel();
            
            nr3d_wt_en.Enabled = !Px_Wt_Man_en.Checked;
            if (nr3d_wt_en.Enabled)
            {
                nr3d_wtEnShowHide(nr3d_wt_en.Checked);
            }
            else
            {
                nr3d_wtEnShowHide(false);
            }
           
            #endregion
         
        }

      
        /// <summary>
        /// 静止像素
        /// </summary>
        private void SetStillPixel() {
            Still_Dnr_Temp0.Text = PixelComputing(Cur_Still_Px_Wt_Gain0.Text, Still_Dnr_Adj_Gain0.Text).ToString("X2");
            Still_Dnr_Temp1.Text = PixelComputing(Cur_Still_Px_Wt_Gain1.Text, Still_Dnr_Adj_Gain1.Text).ToString("X2");
            Still_Dnr_Temp2.Text = PixelComputing(Cur_Still_Px_Wt_Gain2.Text, Still_Dnr_Adj_Gain2.Text).ToString("X2");
            Still_Dnr_Temp3.Text = PixelComputing(Cur_Still_Px_Wt_Gain3.Text, Still_Dnr_Adj_Gain3.Text).ToString("X2");
            Still_Dnr_Temp4.Text = PixelComputing(Cur_Still_Px_Wt_Gain4.Text, Still_Dnr_Adj_Gain4.Text).ToString("X2");
            Still_Dnr_Temp5.Text = PixelComputing(Cur_Still_Px_Wt_Gain5.Text, Still_Dnr_Adj_Gain5.Text).ToString("X2");
            Still_Dnr_Temp6.Text = PixelComputing(Cur_Still_Px_Wt_Gain6.Text, Still_Dnr_Adj_Gain6.Text).ToString("X2");
            Still_Dnr_Temp7.Text = PixelComputing(Cur_Still_Px_Wt_Gain7.Text, Still_Dnr_Adj_Gain7.Text).ToString("X2");
            Still_Dnr_Temp8.Text = PixelComputing(Cur_Still_Px_Wt_Gain8.Text, Still_Dnr_Adj_Gain8.Text).ToString("X2");
        }
        /// <summary>
        /// 运动像素
        /// </summary>
        private void SetMotionPixel() {
            Move_Dnr_Temp0.Text = PixelComputing(Cur_Move_Px_Wt_Gain0.Text, Move_Dnr_Adj_Gain0.Text).ToString("X2");
            Move_Dnr_Temp1.Text = PixelComputing(Cur_Move_Px_Wt_Gain1.Text, Move_Dnr_Adj_Gain1.Text).ToString("X2");
            Move_Dnr_Temp2.Text = PixelComputing(Cur_Move_Px_Wt_Gain2.Text, Move_Dnr_Adj_Gain2.Text).ToString("X2");
            Move_Dnr_Temp3.Text = PixelComputing(Cur_Move_Px_Wt_Gain3.Text, Move_Dnr_Adj_Gain3.Text).ToString("X2");
            Move_Dnr_Temp4.Text = PixelComputing(Cur_Move_Px_Wt_Gain4.Text, Move_Dnr_Adj_Gain4.Text).ToString("X2");
            Move_Dnr_Temp5.Text = PixelComputing(Cur_Move_Px_Wt_Gain5.Text, Move_Dnr_Adj_Gain5.Text).ToString("X2");
            Move_Dnr_Temp6.Text = PixelComputing(Cur_Move_Px_Wt_Gain6.Text, Move_Dnr_Adj_Gain6.Text).ToString("X2");
            Move_Dnr_Temp7.Text = PixelComputing(Cur_Move_Px_Wt_Gain7.Text, Move_Dnr_Adj_Gain7.Text).ToString("X2");
            Move_Dnr_Temp8.Text = PixelComputing(Cur_Move_Px_Wt_Gain8.Text, Move_Dnr_Adj_Gain8.Text).ToString("X2");
        }

        private long PixelComputing(string curpxwt, string dnsadj) {
            if (string.IsNullOrEmpty(curpxwt)||string.IsNullOrEmpty(dnsadj))
            {
                return 0;
            }

            long c1 = Convert.ToInt32(curpxwt, 16);
            long d1 = Convert.ToInt32(dnsadj, 16);

            long temp1 = (128 - c1);
            long temp2 = d1 < 64 ? d1 : (d1 - 128);
            long temp3 = temp1 / 4 + temp2;
            if (temp3 < 0)
            {
                return 0;

            }
            else
            {
                return temp3;
            }
        }

        private void PxWtManEnShowHide(bool isBool) {
            Wt_Pedestal.Enabled = isBool;
            Max_Move_Px_Wt.Enabled = isBool;
            Move_Diff_Ratio.Enabled = isBool;
            Cur_Move_Px_Wt.Enabled = !isBool;
            Cur_Still_Px_Wt.Enabled = !isBool;
        }


        private void nr3d_wtEnShowHide(bool isBool)
        {
            Wt_Pedestalday.Enabled = isBool;
            Wt_Pedestalnight.Enabled = isBool;
            Wt_Pedestalmidnight.Enabled = isBool;
            Max_Move_Px_Wtday.Enabled = isBool;
            Max_Move_Px_Wtnight.Enabled = isBool;
            Max_Move_Px_Wtmidnight.Enabled = isBool;
            Wt_Pedestal.Enabled = !isBool;
            Max_Move_Px_Wt.Enabled = !isBool;
        }
        private void MovePxWtCalEnShowHide(bool isBool) {
            Cur_Move_Px_Wt.Enabled = !isBool;
            Cur_Move_Px_Wt_Gain0.Enabled = isBool;
            Cur_Move_Px_Wt_Gain1.Enabled = isBool;
            Cur_Move_Px_Wt_Gain2.Enabled = isBool;
            Cur_Move_Px_Wt_Gain3.Enabled = isBool;
            Cur_Move_Px_Wt_Gain4.Enabled = isBool;
            Cur_Move_Px_Wt_Gain5.Enabled = isBool;
            Cur_Move_Px_Wt_Gain6.Enabled = isBool;
            Cur_Move_Px_Wt_Gain7.Enabled = isBool;
            Cur_Move_Px_Wt_Gain8.Enabled = isBool;

            if (Parn_en.CheckState != CheckState.Checked && isBool == true)
            {

            }
            else
            {
                labelControl33.Visible = isBool;
                Move_Dnr_Temp0.Visible = isBool;
                Move_Dnr_Temp1.Visible = isBool;
                Move_Dnr_Temp2.Visible = isBool;
                Move_Dnr_Temp3.Visible = isBool;
                Move_Dnr_Temp4.Visible = isBool;
                Move_Dnr_Temp5.Visible = isBool;
                Move_Dnr_Temp6.Visible = isBool;
                Move_Dnr_Temp7.Visible = isBool;
                Move_Dnr_Temp8.Visible = isBool;
            }

               

        }

        private void StillPxWtCalEnShowHide(bool isBool) {
            Cur_Still_Px_Wt.Enabled = !isBool;
            Cur_Still_Px_Wt_Gain0.Enabled = isBool;
            Cur_Still_Px_Wt_Gain1.Enabled = isBool;
            Cur_Still_Px_Wt_Gain2.Enabled = isBool;
            Cur_Still_Px_Wt_Gain3.Enabled = isBool;
            Cur_Still_Px_Wt_Gain4.Enabled = isBool;
            Cur_Still_Px_Wt_Gain5.Enabled = isBool;
            Cur_Still_Px_Wt_Gain6.Enabled = isBool;
            Cur_Still_Px_Wt_Gain7.Enabled = isBool;
            Cur_Still_Px_Wt_Gain8.Enabled = isBool;
            if (Parn_en.CheckState != CheckState.Checked && isBool == true)
            {

            }
            else 
            {
                labelControl17.Visible = isBool;
                Still_Dnr_Temp0.Visible = isBool;
                Still_Dnr_Temp1.Visible = isBool;
                Still_Dnr_Temp2.Visible = isBool;
                Still_Dnr_Temp3.Visible = isBool;
                Still_Dnr_Temp4.Visible = isBool;
                Still_Dnr_Temp5.Visible = isBool;
                Still_Dnr_Temp6.Visible = isBool;
                Still_Dnr_Temp7.Visible = isBool;
                Still_Dnr_Temp8.Visible = isBool;
            }
            
        }

        private void ThreeDParnEnShowHide(bool isBool) {
            Move_Dnr_Adj_Gain0.Enabled = isBool;
            Move_Dnr_Adj_Gain1.Enabled = isBool;
            Move_Dnr_Adj_Gain2.Enabled = isBool;
            Move_Dnr_Adj_Gain3.Enabled = isBool;
            Move_Dnr_Adj_Gain4.Enabled = isBool;
            Move_Dnr_Adj_Gain5.Enabled = isBool;
            Move_Dnr_Adj_Gain6.Enabled = isBool;
            Move_Dnr_Adj_Gain7.Enabled = isBool;
            Move_Dnr_Adj_Gain8.Enabled = isBool;
            Still_Dnr_Adj_Gain0.Enabled = isBool;
            Still_Dnr_Adj_Gain1.Enabled = isBool;
            Still_Dnr_Adj_Gain2.Enabled = isBool;
            Still_Dnr_Adj_Gain3.Enabled = isBool;
            Still_Dnr_Adj_Gain4.Enabled = isBool;
            Still_Dnr_Adj_Gain5.Enabled = isBool;
            Still_Dnr_Adj_Gain6.Enabled = isBool;
            Still_Dnr_Adj_Gain7.Enabled = isBool;
            Still_Dnr_Adj_Gain8.Enabled = isBool;

            if (isBool && Move_Px_Wt_Cal_en.CheckState != CheckState.Checked)
            {
                
            }
            else
            {
                labelControl33.Visible = isBool;
                Move_Dnr_Temp0.Visible = isBool;
                Move_Dnr_Temp1.Visible = isBool;
                Move_Dnr_Temp2.Visible = isBool;
                Move_Dnr_Temp3.Visible = isBool;
                Move_Dnr_Temp4.Visible = isBool;
                Move_Dnr_Temp5.Visible = isBool;
                Move_Dnr_Temp6.Visible = isBool;
                Move_Dnr_Temp7.Visible = isBool;
                Move_Dnr_Temp8.Visible = isBool;
            }

            if (isBool && Still_Px_Wt_Cal_en.CheckState != CheckState.Checked)
            {

            }
            else
            {
                labelControl17.Visible = isBool;
                Still_Dnr_Temp0.Visible = isBool;
                Still_Dnr_Temp1.Visible = isBool;
                Still_Dnr_Temp2.Visible = isBool;
                Still_Dnr_Temp3.Visible = isBool;
                Still_Dnr_Temp4.Visible = isBool;
                Still_Dnr_Temp5.Visible = isBool;
                Still_Dnr_Temp6.Visible = isBool;
                Still_Dnr_Temp7.Visible = isBool;
                Still_Dnr_Temp8.Visible = isBool;
            }
           

        }

        private void RawGslAndRawRbslShowHide(bool isBool)
        {
            Raw_Gsl0.Enabled = isBool;
            Raw_Gsl1.Enabled = isBool;
            Raw_Gsl2.Enabled = isBool;
            Raw_Gsl3.Enabled = isBool;
            Raw_Gsl4.Enabled = isBool;
            Raw_Gsl5.Enabled = isBool;
            Raw_Gsl6.Enabled = isBool;
            Raw_Gsl7.Enabled = isBool;
            Raw_Gsl8.Enabled = isBool;
            Raw_Gsl9.Enabled = isBool;
            Raw_Rbsl0.Enabled = isBool;
            Raw_Rbsl1.Enabled = isBool;
            Raw_Rbsl2.Enabled = isBool;
            Raw_Rbsl3.Enabled = isBool;
            Raw_Rbsl4.Enabled = isBool;
            Raw_Rbsl5.Enabled = isBool;
            Raw_Rbsl6.Enabled = isBool;
            Raw_Rbsl7.Enabled = isBool;
            Raw_Rbsl8.Enabled = isBool;
            Raw_Rbsl9.Enabled = isBool;
        }
        private void UvDnsManualShowHide(bool isBool) {
            Uv_Dnr0.Enabled = isBool;
            Uv_Dnr1.Enabled = isBool;
            Uv_Dnr2.Enabled = isBool;
            Uv_Dnr3.Enabled = isBool;
            Uv_Dnr4.Enabled = isBool;
            Uv_Dnr5.Enabled = isBool;
            Uv_Dnr6.Enabled = isBool;
            Uv_Dnr7.Enabled = isBool;
            Uv_Dnr8.Enabled = isBool;
            Uv_Dnr9.Enabled = isBool;
            Uv_DNR_Manual.Enabled = !isBool;
        }
        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void XChip_DNS_Load(object sender, EventArgs e)
        {
            //if (ConfigurationManager.AppSettings["xcEdition"] == "1") {
            //    simpleButton1.Text = "获取参数";
            //    simpleButton6.Text = "调试指南";
            //}
            //group3ddnr.Hide();
            Task.Run(() => {
            this.Invoke((EventHandler)delegate {
                for (int i = 0; i < XChipDnr.Count; i++)
                {

                    var type = AppHelper.NameTypeToString(XChipDnr[i].NameType);
                    //加上单选框的_en
                    if (XChipDnr[i].ControlType == "1")
                    {
                        type = XChipDnr[i].NameType;
                    }
                    try
                    {
                        var col = this.Controls.Find(type, true);


                        foreach (var item in col)
                        {
                            if (item is TextEdit)
                            {
                                //声明一个SuerToolTip
                                DevExpress.Utils.SuperToolTip graduationBatchSuperToolTip = new DevExpress.Utils.SuperToolTip();
                                //声明一个ToolTipTitleItem,保存标题
                                DevExpress.Utils.ToolTipTitleItem toolTipTitleItem = new DevExpress.Utils.ToolTipTitleItem();
                                String tooltips = "";

                                if (!string.IsNullOrEmpty(XChipDnr[i].Bit_Wide))
                                {
                                    tooltips += $"位宽={XChipDnr[i].Bit_Wide}";
                                }
                                if (!string.IsNullOrEmpty(XChipDnr[i].Bit_Accuracy))
                                {
                                    tooltips += $"|精度={XChipDnr[i].Bit_Accuracy}";
                                }
                                //设置标题文字
                                toolTipTitleItem.Text = tooltips;
                                //把标题添加到SuerToolTip
                                graduationBatchSuperToolTip.Items.Add(toolTipTitleItem);
                                //指定控件的SuperTip
                                ((TextEdit)item).SuperTip = graduationBatchSuperToolTip;
                                //正则判断
                                ((TextEdit)item).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                                ((TextEdit)item).Properties.Mask.EditMask = BitsHelp.GetBitsToMask(XChipDnr[i].Bits, XChipDnr[i].Bit_Wide, XChipDnr.Where(c => c.NameType.ToLower().Contains(type) && c.ControlType == "0").Select(c => c.Bits).ToList());
                            }
                            }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            });
            });
        }
        #endregion
    
        private async Task SetDnsRegister(addressregister model, ulong add, bool isCheck = true)
        {
            if (isRead) return;

            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetDnsRegister 写入失败 - 地址: {model.Address}, 值: {add:X}");
            }

        }
        #region 勾选框changed
        private async void PxWtManEn_CheckedChanged(object sender, EventArgs e)
        {
            var txt = sender as CheckEdit;
            if (isRead) return;
            nr3d_wt_en.Enabled = !txt.Checked;
            if (nr3d_wt_en.Enabled)
            {
                nr3d_wtEnShowHide(nr3d_wt_en.Checked);
            }
            else
            {
                nr3d_wtEnShowHide(false);
            }
            if (Px_Wt_Man_en.CheckState == CheckState.Checked) //这个是勾选下发值
            {
                if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), Px_Wt_Man_en.Checked);
                    SetDnsRegister(model, Val);
                }
                if (XChipDnr.Exists(c => c.NameType.ToLower() == ("Px_Wt_Man3_en").ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == ("Px_Wt_Man3_en").ToLower());
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex,  Add.ToString("X2"), Px_Wt_Man_en.Checked);
                    SetDnsRegister(model, Val);
                }
                PxWtManEnShowHide(false);
                Move_Px_Wt_Cal_en.Enabled = true;
                Still_Px_Wt_Cal_en.Enabled = true;

                MovePxWtCalEnShowHide(Move_Px_Wt_Cal_en.Checked);
                StillPxWtCalEnShowHide(Still_Px_Wt_Cal_en.Checked);

                if (Move_Px_Wt_Cal_en.CheckState == CheckState.Checked|| Move_Px_Wt_Cal_en.CheckState == CheckState.Checked)
                {
                    var Adden = await ReadRegisterAsync("200014de");
                    var Valen = BitsHelp.SetBitsCheckedToUint("[0]", "1", Adden.ToString("X2"), true);
                    await WriteRegisterAsync(0x200014de.ToString("X"), Valen.ToString("X"));
                }
            }
            else
            {
                if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), Px_Wt_Man_en.Checked);
                    SetDnsRegister(model, Val);
                }
                if (XChipDnr.Exists(c => c.NameType.ToLower() == ("Px_Wt_Man3_en").ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == ("Px_Wt_Man3_en").ToLower());
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), Px_Wt_Man_en.Checked);
                    SetDnsRegister(model, Val);
                }
                PxWtManEnShowHide(true);
                Move_Px_Wt_Cal_en.Enabled = false;
                Still_Px_Wt_Cal_en.Enabled = false;
                MovePxWtCalEnShowHide(false);
                StillPxWtCalEnShowHide(false);
                Cur_Move_Px_Wt.Enabled = false;
                Cur_Still_Px_Wt.Enabled = false;


                var  Adden = await ReadRegisterAsync("200014de");
                var  Valen = BitsHelp.SetBitsCheckedToUint("[0]", "1", Adden.ToString("X2"), false);
                await WriteRegisterAsync(0x200014de.ToString("X"), Valen.ToString("X"));

            }
            
        }

        private async void MovePxWtCalEn_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txt = sender as CheckEdit;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), Move_Px_Wt_Cal_en.Checked);
                SetDnsRegister(model, Val);
            }
            if (Move_Px_Wt_Cal_en.CheckState == CheckState.Checked)
            {
                if (Px_Wt_Man_en.CheckState == CheckState.Checked)
                {
                    MovePxWtCalEnShowHide(true);
                }
                else
                {
                    MovePxWtCalEnShowHide(false);
                }
                var Adden = await ReadRegisterAsync("200014de");
                var Valen = BitsHelp.SetBitsCheckedToUint("[0]", "1", Adden.ToString("X2"), true);
                await WriteRegisterAsync(0x200014de.ToString("X"), Valen.ToString("X"));
            }
            else
            {
                MovePxWtCalEnShowHide(false);
                if (Move_Px_Wt_Cal_en.CheckState != CheckState.Checked)
                {
                    var Adden = await ReadRegisterAsync("200014de");
                    var Valen = BitsHelp.SetBitsCheckedToUint("[0]", "1", Adden.ToString("X2"), false);
                    await WriteRegisterAsync(0x200014de.ToString("X"), Valen.ToString("X"));
                }
            }
        }

        private async void StillPxWtCalEn_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txt = sender as CheckEdit;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), txt.Checked);
                SetDnsRegister(model, Val);
            }
            if (Still_Px_Wt_Cal_en.CheckState == CheckState.Checked)
            {
                if (Px_Wt_Man_en.CheckState == CheckState.Checked)
                {
                    StillPxWtCalEnShowHide(true);
                }
                else
                {
                    StillPxWtCalEnShowHide(false);
                }
                var Adden = await ReadRegisterAsync("200014de");
                var Valen = BitsHelp.SetBitsCheckedToUint("[0]", "1", Adden.ToString("X2"), true);
                await WriteRegisterAsync(0x200014de.ToString("X"), Valen.ToString("X"));

            }
            else
            {
                StillPxWtCalEnShowHide(false);
                if (Move_Px_Wt_Cal_en.CheckState != CheckState.Checked)
                {
                    var Adden = await ReadRegisterAsync("200014de");
                    var Valen = BitsHelp.SetBitsCheckedToUint("[0]", "1", Adden.ToString("X2"), false);
                    await WriteRegisterAsync(0x200014de.ToString("X"), Valen.ToString("X"));
                }
            }
        }

        private async void ParnEn_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txt = sender as CheckEdit;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                //bit1置0才是勾选所以要反一下
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), !Parn_en.Checked);
                SetDnsRegister(model, Val);
            }
            if (Parn_en.CheckState == CheckState.Checked)
            {
                ThreeDParnEnShowHide(true);
                RawGslAndRawRbslShowHide(false);
            }
            else
            {
                ThreeDParnEnShowHide(false);
                RawGslAndRawRbslShowHide(true);
            }
        }

        private async void UvDNSManualEn_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txt = sender as DevExpress.XtraEditors.TextEdit;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), Uv_DNR_Manual_En.Checked);
                SetDnsRegister(model, Val);
            }
            if (Uv_DNR_Manual_En.CheckState == CheckState.Checked)
            {
                Uv_DNR_Manual_En.CheckState = CheckState.Checked;
                UvDnsManualShowHide(false);
            }
            else
            {
                Uv_DNR_Manual_En.CheckState = CheckState.Unchecked;
                UvDnsManualShowHide(true);
            }
        }
        #endregion

        private void RawSigma0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetDnsRegister(model, Val);
                }
            }
        }

        private void RawGsl0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetDnsRegister(model, Val);
                }
            }
        }

        private void RawRbsl0_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            //if (string.IsNullOrEmpty(txtEdit.Text)) return;
            //switch (txtEdit.Tag.ToString())
            //{
            //    case "0": SetDnsRegister("RawRbsl0", (ulong)Convert.ToInt32(Raw_Rbsl0.Text, 16)); break;
            //    case "1": SetDnsRegister("RawRbsl1", (ulong)Convert.ToInt32(Raw_Rbsl1.Text, 16)); break;
            //    case "2": SetDnsRegister("RawRbsl2", (ulong)Convert.ToInt32(Raw_Rbsl2.Text, 16)); break;
            //    case "3": SetDnsRegister("RawRbsl3", (ulong)Convert.ToInt32(Raw_Rbsl3.Text, 16)); break;
            //    case "4": SetDnsRegister("RawRbsl4", (ulong)Convert.ToInt32(Raw_Rbsl4.Text, 16)); break;
            //    case "5": SetDnsRegister("RawRbsl5", (ulong)Convert.ToInt32(Raw_Rbsl5.Text, 16)); break;
            //    case "6": SetDnsRegister("RawRbsl6", (ulong)Convert.ToInt32(Raw_Rbsl6.Text, 16)); break;
            //    case "7": SetDnsRegister("RawRbsl7", (ulong)Convert.ToInt32(Raw_Rbsl7.Text, 16)); break;
            //    case "8":
            //        SetDnsRegister("RawRbsl8", (ulong)Convert.ToInt32(Raw_Rbsl8.Text, 16));
            //        SetDnsRegister("RawRbsl9", (ulong)Convert.ToInt32(Raw_Rbsl8.Text, 16)); break;
            //    case "9": SetDnsRegister("RawRbsl9", (ulong)Convert.ToInt32(Raw_Rbsl9.Text, 16)); break;
            //    default:
            //        break;
            //}
        }

        private void YuvSigma0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetDnsRegister(model, Val);
                }
            }
        }

        private void Ysl0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetDnsRegister(model, Val);
                }
            }
        }

        private void UvDns0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetDnsRegister(model, Val);
                }
            }
        }

        private void UvDnsManual_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (isRead) return; //判断是否在读，读的时候不进行写           
            if (string.IsNullOrEmpty(Uv_DNR_Manual.Text)) return;
            var txt = sender as DevExpress.XtraEditors.TextEdit;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Uv_DNR_Manual.Text);
                SetDnsRegister(model, Val);
            }
        }

        private void WtPedestal_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetDnsRegister(model, Val);
                }
            }
        }

        private void CurMovePxWt_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (isRead) return; //判断是否在读，读的时候不进行写           
            if (string.IsNullOrEmpty(Cur_Move_Px_Wt.Text)) return;
            var txt = sender as DevExpress.XtraEditors.TextEdit;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Cur_Move_Px_Wt.Text);
                SetDnsRegister(model, Val);
            }

        }

        private void CurStillPxWt_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (isRead) return; //判断是否在读，读的时候不进行写           
            if (string.IsNullOrEmpty(Cur_Still_Px_Wt.Text)) return;
            var txt = sender as DevExpress.XtraEditors.TextEdit;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Cur_Still_Px_Wt.Text);
                SetDnsRegister(model, Val);
            }
        }

        private void Slope0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetDnsRegister(model, Val);
                }
            }
        }

        private void Offset0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetDnsRegister(model, Val);
                }
            }
        }

        private void CurMovePxWtGain0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetDnsRegister(model, Val);
                }
            }
            SetMotionPixel();
            SetStillPixel();
        }

        private void CurStillPxWtGain0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetDnsRegister(model, Val);
                }
            }
            SetMotionPixel();
            SetStillPixel();
        }

        private void MoveDnsAdjGain0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                var nValue = Convert.ToUInt32(txt.Text, 16);
                if (nValue > 0x7f)
                {
                    if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                    {
                        var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "7F");
                        SetDnsRegister(model, Val);
                    }
                    txt.Text = "7F";
                }
                else
                {
                    if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                    {
                        var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetDnsRegister(model, Val);
                    }
                }
                
            }
            SetMotionPixel();
            SetStillPixel();
        }

        private void StillDnsAdjGain0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                var nValue = Convert.ToUInt32(txt.Text, 16);
                if (nValue > 0x7f)
                {
                    if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                    {
                        var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "7F");
                        SetDnsRegister(model, Val);
                    }
                    txt.Text = "7F";
                }
                else
                {
                    if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                    {
                        var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetDnsRegister(model, Val);
                    }
                }

            }
            SetMotionPixel();
            SetStillPixel();
        }

        private void RawSigma0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                RawSigma0_Leave(sender, null);
            }
        }

        private void RawGsl0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                RawGsl0_Leave(sender, null);
            }
        }

        private void RawRbsl0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                RawRbsl0_Leave(sender, null);
            }
        }

        private void YuvSigma0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                YuvSigma0_Leave(sender, null);
            }
        }

        private void Ysl0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Ysl0_Leave(sender, null);
            }
        }

        private void UvDns0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                UvDns0_Leave(sender, null);
            }
        }

        private void UvDnsManual_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                UvDnsManual_Leave(sender, null);
            }
        }

        private void WtPedestal_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                WtPedestal_Leave(sender, null);
            }
        }

        private void CurMovePxWt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                CurMovePxWt_Leave(sender, null);
            }
        }

        private void CurStillPxWt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                CurStillPxWt_Leave(sender, null);
            }
        }

        private void Slope0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Slope0_Leave(sender, null);
            }
        }

        private void Offset0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Offset0_Leave(sender, null);
            }
        }

        private void CurMovePxWtGain0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                CurMovePxWtGain0_Leave(sender, null);
            }
        }

        private void CurStillPxWtGain0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                CurStillPxWtGain0_Leave(sender, null);
            }
        }

        private void MoveDnsAdjGain0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                MoveDnsAdjGain0_Leave(sender, null);
            }
        }

        private void StillDnsAdjGain0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                StillDnsAdjGain0_Leave(sender, null);
            }
        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            //string str = "       根据不同增益值，调节RAW域或YUV域的去噪等级；\r\n       其中 Raw_Sigma 值越大去噪越强；Gsl/Rbsl 值越大去噪越弱（取值范围为 0x00~0x20），分别决定 G 分量上和 RB 分量上的去噪程度，作用于RAW域中。Yuv_Sigma 值越大去噪越强；Ysl值越大去噪越弱（取值范围为 0x00~0x20），且主要决定 Y 分量上的去噪程度；Uv_dns 值越大，彩噪的去噪程度越强，作用于 YUV 域中。\r\n       部分型号isp支持时域去噪（3DNR）；其中“Px_Wt_Man_en”未勾选，则为3DNR 的强度自动调节模式，Wt_Pedestal 的取值范围为 0x00~0x80，值越大，3D 去噪越强，运动拖尾越严重；勾选后，则为3DNR 的强度手动调节模式，同Cur_Move_Px_Wt_Gain与Cur_Still_Px_Wt_Gain联调，设置不同增益下的 3DNR 强度，取值范围为 0x00~0x80，值越大，3D 去噪越弱。\r\n       更多详见《调试工具用户手册》。";
            Thread thread = new Thread(threadPro);
            thread.Start();
        }
        private void threadPro()

        {

            MethodInvoker methodInvoker = new MethodInvoker(ShowFormB);

            BeginInvoke(methodInvoker);

        }

        private void ShowFormB()
        {
            //string str = "\t      \t 根据不同增益值，调节RAW域或YUV域的去噪等级；\r\n"
            //   + "\t      \t 其中 Raw_Sigma 值越大去噪越强；Gsl/Rbsl 值越大去噪越弱（取值范围为 0x00~0x20），分别决定 G 分量上和 RB 分量上的去噪程度，作用于RAW域中。Yuv_Sigma 值越大去噪越强；Ysl值越大去噪越弱（取值范围为 0x00~0x20），且主要决定 Y 分量上的去噪程度；Uv_dns 值越大，彩噪的去噪程度越强，作用于 YUV 域中。\r\n"
            //   + "\t      \t 部分型号isp支持时域去噪（3DNR）；其中“Px_Wt_Man_en”未勾选，则为3DNR 的强度自动调节模式，Wt_Pedestal 的取值范围为 0x00~0x80，值越大，3D 去噪越强，运动拖尾越严重；勾选后，则为3DNR 的强度手动调节模式，同Cur_Move_Px_Wt_Gain与Cur_Still_Px_Wt_Gain联调，设置不同增益下的 3DNR 强度，取值范围为 0x00~0x80，值越大，3D 去噪越弱。\r\n"
            //   + "\t      \t 为减少和消除对于噪声的放大效应，Med_filter_scale用来调节滤波的强度，值越大，滤波越强，同时通过调节thr_slope/thr_offset控制噪声模型曲线，噪声曲线越陡峭时，对应的降噪效果越强。\r\n"
            //   + "\t      \t Lap_enhance_scale为增强倍率，其中 value =0x10 为 1 倍增强，value <0x10为小于 1 倍增强，value >0x10 为大于 1 倍增强。\r\n"
            //   + "\t      \t 更多详见《调试工具用户手册》。\r\n";
            string str = "";
            XChip_OptimizationTips ot = new XChip_OptimizationTips("DNS调优Tips", str);
            ot.StartPosition = FormStartPosition.CenterScreen;
            //ot.ShowDialog();
            ot.Show();

        }

        private void txt_Lap_enhance_scale_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if(e.KeyCode == Keys.Enter)
                {
                    if (isWrite) return;
                    if (isRead) return; //判断是否在读，读的时候不进行写           
                    if (string.IsNullOrEmpty(Uv_DNR_Manual.Text)) return;
                    if (XChipDnr.Exists(c => c.NameType.ToLower() == ($"Lap_enhance_scale").ToLower()))
                    {
                        var model = XChipDnr.Find(c => c.NameType.ToLower() == ($"Lap_enhance_scale").ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Lap_enhance_scale.Text);
                        SetDnsRegister(model, Val);
                    }
                }
            }
        }

        private void txt_Lap_enhance_scale_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_Lap_enhance_scale_KeyDown(sender, keyEnter);
        }

        private void txt_Med_filter_sclae_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (isWrite) return;
                if (isRead) return; //判断是否在读，读的时候不进行写           
                if (string.IsNullOrEmpty(Uv_DNR_Manual.Text)) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Med_filter_sclae.Text);
                    SetDnsRegister(model, Val);
                }
            }
        }

        private void txt_Med_filter_sclae_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_Med_filter_sclae_KeyDown(sender, keyEnter);
        }

        private void txt_thr_slope_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_thr_slope_man_KeyDown(sender, keyEnter);
        }

        private void txt_thr_slope_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (isWrite) return;
                {
                    if (isRead) return;
                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                    if (string.IsNullOrEmpty(txt.Text)) return;
                    if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                    {
                        var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetDnsRegister(model, Val);
                    }
                }
            }
        }

        private void txt_thr_offset_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (isWrite) return;
                {
                    if (isRead) return;
                    var txt = sender as DevExpress.XtraEditors.TextEdit;
                    if (string.IsNullOrEmpty(txt.Text)) return;
                    if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                    {
                        var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetDnsRegister(model, Val);
                    }
                }
            }
        }

        private void txt_thr_offset_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_thr_offset_man_KeyDown(sender, keyEnter);
        }
        private void SetTxtSlopeMan_Enable(bool isbool)
        {
            soft_thr_slope_man.Enabled = isbool;

            thr_slope_1x.Enabled = !isbool;
            thr_slope_2x.Enabled = !isbool;
            thr_slope_4x.Enabled = !isbool;
            thr_slope_8x.Enabled = !isbool;
            thr_slope_16x.Enabled = !isbool;
            thr_slope_32x.Enabled = !isbool;
            thr_slope_64x.Enabled = !isbool;
            thr_slope_128x.Enabled = !isbool;
            thr_slope_256x.Enabled = !isbool;          
        }
        private void SetTxtOffsetMan_Enable(bool isbool)
        {

            soft_thr_offset_man.Enabled = isbool;

            thr_offset_1x.Enabled = !isbool;
            thr_offset_2x.Enabled = !isbool;
            thr_offset_4x.Enabled = !isbool;
            thr_offset_8x.Enabled = !isbool;
            thr_offset_16x.Enabled = !isbool;
            thr_offset_32x.Enabled = !isbool;
            thr_offset_64x.Enabled = !isbool;
            thr_offset_128x.Enabled = !isbool;
            thr_offset_256x.Enabled = !isbool;
        }


        private async void chk_thr_slope_man_CheckedChanged(object sender, EventArgs e)
        {
            SetTxtSlopeMan_Enable(soft_thr_slope_man_en.Checked);
            if (isRead) return;
            var txt = sender as CheckEdit;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), txt.Checked);
                SetDnsRegister(model, Val);
            }
        }

        private async void chk_thr_offset_man_CheckedChanged(object sender, EventArgs e)
        {
            SetTxtOffsetMan_Enable(soft_thr_offset_man_en.Checked);
            if (isRead) return;
            var txt = sender as CheckEdit;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), txt.Checked);
                SetDnsRegister(model, Val);
            }
        }

        private async void simpleButton4_Click(object sender, EventArgs e)
        {
            //SerialSend.isDebug = false;
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "配置文件（*.txt）|*.txt";

            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "IQ_Setting_DNR_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK) {
                var Pe_dal = new parameter_exportManager();
                if (null != Pe_dal) {
                    WaitBefore.Start("参数导出", "正在加载中", 60);
                    //var tempList = Pe_dal.GetList(c => c.Module == "AWB");
                    var tempList = Pe_dal.GetListToExport().Where(c => c.Module == "3D DNR"||
                    c.Module == "RAW DNR"||
                    c.Module == "YUV DNR"||
                    c.Module == "UV DNR").OrderBy(c => c.SortNum).ToList();
                    #region 判断是否需要用白天的数据
                    var Pe_patch_dal = new parameter_export_patchManager();
                    var patchList = Pe_patch_dal.GetList();
                    var conditionList = tempList.Select(c => c.ConditionAddr).Distinct();
                    foreach (var item in conditionList)
                    {
                        if (await ReadRegisterAsync(item) == 0)
                        {
                            patchList.RemoveAll(c => c.ConditionAddr == item);
                        }
                    }
                    #endregion
                  
                }
                WaitBefore.Close();
                DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
            }
        }

        private void simpleButton1_MouseEnter(object sender, EventArgs e)
        {
            isWrite = true;
        }

        private void simpleButton1_MouseLeave(object sender, EventArgs e)
        {
            isWrite = false;
        }

       
        private void lap_enhancement_Enable(bool isbool)
        {
            soft_thr_slope_man_en.Enabled = isbool;
            soft_thr_slope_man.Enabled = isbool;
            thr_slope_1x.Enabled = isbool;
            thr_slope_2x.Enabled = isbool;
            thr_slope_4x.Enabled = isbool;
            thr_slope_8x.Enabled = isbool;
            thr_slope_16x.Enabled = isbool;
            thr_slope_32x.Enabled = isbool;
            thr_slope_64x.Enabled = isbool;
            thr_slope_128x.Enabled = isbool;
            thr_slope_256x.Enabled = isbool;

            soft_thr_offset_man_en.Enabled = isbool;
            soft_thr_offset_man.Enabled = isbool;
            thr_offset_1x.Enabled = isbool;
            thr_offset_2x.Enabled = isbool;
            thr_offset_4x.Enabled = isbool;
            thr_offset_8x.Enabled = isbool;
            thr_offset_16x.Enabled = isbool;
            thr_offset_32x.Enabled = isbool;
            thr_offset_64x.Enabled = isbool;
            thr_offset_128x.Enabled = isbool;
            thr_offset_256x.Enabled = isbool;

            soft_thr_en.Enabled = isbool;
            Med_filter_sclae.Enabled = isbool;
            Lap_enhance_scale.Enabled = isbool;
            soft_thr_slope_man.Enabled = isbool;
            soft_thr_offset_man.Enabled = isbool;
        }

        private async void lap_enhancement_en_CheckedChanged(object sender, EventArgs e)
        {
            
            if (isRead) return;
            var txt = sender as CheckEdit;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), txt.Checked);
                SetDnsRegister(model, Val);
            }
            if (lap_enhancement_en.CheckState == CheckState.Checked)
            {
                lap_enhancement_Enable(true);
                if (soft_thr_en.CheckState == CheckState.Checked)
                {
                    soft_thr_Enable(true);
                    SetTxtSlopeMan_Enable(soft_thr_slope_man_en.Checked);
                    SetTxtOffsetMan_Enable(soft_thr_offset_man_en.Checked);
                }
                else
                {
                    soft_thr_Enable(false);
                }
                
            }
            else
            {
                lap_enhancement_Enable(false);
            }
        }
        private void soft_thr_Enable(bool isbool)
        {

            thr_slope_1x.Enabled = isbool;
            thr_slope_2x.Enabled = isbool;
            thr_slope_4x.Enabled = isbool;
            thr_slope_8x.Enabled = isbool;
            thr_slope_16x.Enabled = isbool;
            thr_slope_32x.Enabled = isbool;
            thr_slope_64x.Enabled = isbool;
            thr_slope_128x.Enabled = isbool;
            thr_slope_256x.Enabled = isbool;


            thr_offset_1x.Enabled = isbool;
            thr_offset_2x.Enabled = isbool;
            thr_offset_4x.Enabled = isbool;
            thr_offset_8x.Enabled = isbool;
            thr_offset_16x.Enabled = isbool;
            thr_offset_32x.Enabled = isbool;
            thr_offset_64x.Enabled = isbool;
            thr_offset_128x.Enabled = isbool;
            thr_offset_256x.Enabled = isbool;

        }
        private async void soft_thr_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txt = sender as CheckEdit;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), txt.Checked);
                SetDnsRegister(model, Val);
            }
            if (soft_thr_en.CheckState == CheckState.Checked)
            {
                soft_thr_Enable(true);
                SetTxtSlopeMan_Enable(soft_thr_slope_man_en.Checked);
                SetTxtOffsetMan_Enable(soft_thr_offset_man_en.Checked);
                soft_thr_offset_man_en.Enabled = true;
                soft_thr_slope_man_en.Enabled = true;
                if (soft_thr_offset_man_en.Checked)
                {
                    soft_thr_offset_man.Enabled = true;
                }
                if (soft_thr_slope_man_en.Checked)
                {
                    soft_thr_slope_man.Enabled = true;
                }

            }
            else
            {
                soft_thr_Enable(false);
                soft_thr_offset_man_en.Enabled = false;
                soft_thr_slope_man_en.Enabled = false;
                soft_thr_slope_man.Enabled = false;
                soft_thr_offset_man.Enabled = false;
            }
        }

        private async void nr3d_wt_en_CheckedChanged(object sender, EventArgs e)
        {
            var txt = sender as CheckEdit;
            nr3d_wtEnShowHide(txt.Checked);
            if (isRead) return;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                //bit1置0才是勾选所以要反一下
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), txt.Checked);
                SetDnsRegister(model, Val);
            }
            
        }

        private void Wt_Pedestalday_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (isWrite) return;
                if (isRead) return; //判断是否在读，读的时候不进行写           
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetDnsRegister(model, Val);
                }
            }
        }

        private void Wt_Pedestalday_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            Wt_Pedestalday_KeyDown(sender, keyEnter);
        }

        /// <summary>
        /// 异步读取单个寄存器并更新文本框
        /// </summary>
        private async Task ReadRegisterAndUpdateTextAsync(string address, TextEdit textEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");

                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    string processedValue = record.Values;
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    Console.WriteLine($"[ADBForm] 成功读取寄存器 {address} 值: {processedValue}");

                    // 处理位操作
                    string displayValue;
                    if (processedValue != "0")
                    {
                        var uintValue = BitsHelp.GetBitsToUint(bits, hex, processedValue);
                        displayValue = uintValue.ToString("X");
                        Console.WriteLine($"[ADBForm] 寄存器 {address} Bits处理后值: {displayValue} (bits:{bits}, hex:{hex})");
                    }
                    else
                    {
                        displayValue = "0";
                    }

                    // 更新UI
                    UpdateTextEdit(textEdit, displayValue);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    UpdateTextEdit(textEdit, "0");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 异步读取多个寄存器并组合更新文本框
        /// </summary>
        private async Task ReadMultipleRegistersAndUpdateTextAsync(List<addressregister> nList, TextEdit textEdit)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取多个寄存器，数量: {nList.Count}");

                string combinedValue = string.Empty;

                // 按预定义的优先级顺序读取寄存器
                var priorityOrder = new[] { "_h", "_m0", "_m1", "_m2", "_m3", "_l" };

                foreach (var priority in priorityOrder)
                {
                    addressregister register = FindRegisterByPriority(nList, priority);

                    if (register != null)
                    {
                        Console.WriteLine($"[ADBForm] 读取优先级 '{priority}' 的寄存器: {register.NameType} ({register.Address})");

                        // 发送读取命令
                        string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{register.Address},0,0\"";
                        adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{register.Address}");

                        // 等待命令执行
                        await Task.Delay(10);

                        // 获取寄存器值
                        var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(register.Address, "Read", 500));

                        if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                        {
                            string processedValue = record.Values;
                            if (processedValue.StartsWith("0x"))
                            {
                                processedValue = processedValue.Substring(2);
                            }

                            combinedValue += processedValue.PadLeft(2, '0');
                            Console.WriteLine($"[ADBForm] 成功读取 {register.Address}，当前组合值: {combinedValue}");
                        }
                        else
                        {
                            combinedValue += "00";
                            Console.WriteLine($"[ADBForm] 读取 {register.Address} 失败，使用默认值00，当前组合值: {combinedValue}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 未找到包含 '{priority}' 的寄存器");
                    }
                }

                Console.WriteLine($"[ADBForm] 最终组合值: {combinedValue}");

                // 更新UI
                UpdateTextEdit(textEdit, combinedValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取多个寄存器失败: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 根据优先级查找寄存器
        /// </summary>
        private addressregister FindRegisterByPriority(List<addressregister> nList, string priority)
        {
            if (priority == "_l")
            {
                // 特殊处理 _l 寄存器
                if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                {
                    // 首先查找以 "_l" 结尾的寄存器
                    var exactMatch = nList.Find(c => c.NameType.ToLower().EndsWith("_l"));
                    if (exactMatch != null)
                    {
                        Console.WriteLine($"[ADBForm] 找到以 '_l' 结尾的寄存器: {exactMatch.NameType}");
                        return exactMatch;
                    }
                    else
                    {
                        // 如果没有以 "_l" 结尾的，则使用最后一个包含 "_l" 的寄存器
                        var containsMatch = nList.Last(c => c.NameType.ToLower().Contains("_l"));
                        Console.WriteLine($"[ADBForm] 找到包含 '_l' 的寄存器: {containsMatch.NameType}");
                        return containsMatch;
                    }
                }
            }
            else
            {
                // 其他寄存器正常处理
                var register = nList.Find(c => c.NameType.ToLower().Contains(priority));
                if (register != null)
                {
                    Console.WriteLine($"[ADBForm] 找到包含 '{priority}' 的寄存器: {register.NameType}");
                    return register;
                }
            }

            return null;
        }

        /// <summary>
        /// 更新文本框的辅助方法
        /// </summary>
        private void UpdateTextEdit(TextEdit textEdit, string value)
        {
            if (textEdit.InvokeRequired)
            {
                textEdit.Invoke(new Action(() =>
                {
                    textEdit.Text = value;
                    Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
                }));
            }
            else
            {
                textEdit.Text = value;
                Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
            }
        }

        /// <summary>
        /// 异步读取寄存器并更新复选框
        /// </summary>
        private async Task ReadRegisterAndUpdateCheckAsync(string address, CheckEdit checkEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器并更新复选框: {address}");

                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                bool isChecked = false;
                if (!string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    isChecked = BitsHelp.GetBitsCheckedToBool(bits, hex, record.Values) == 0;
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值:{record.Values}, 状态:{isChecked}");
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值无效, 状态:false");
                }

                // 更新UI
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = isChecked));
                }
                else
                {
                    checkEdit.Checked = isChecked;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 更新复选框失败: {ex.Message}");
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = false));
                }
                else
                {
                    checkEdit.Checked = false;
                }
            }
        }

        /// <summary>
        /// 异步读取单个寄存器返回值
        /// </summary>
        private async Task<long> ReadRegisterAsync(string address)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");
                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    return Convert.ToInt32(record.Values,16);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    return 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                return 0;
            }
        }
        /// <summary>
        /// 异步写入单个寄存器，在值不匹配时自动重试一次
        /// </summary>
        private async Task<bool> WriteRegisterAsync(string address, string value)
        {
            int maxRetries = 1; // 值不匹配时最多重试一次
            int retryCount = 0;

            while (retryCount <= maxRetries)
            {
                try
                {
                    if (retryCount > 0)
                    {
                        Console.WriteLine($"[ADBForm] 第 {retryCount} 次重试写入寄存器: {address} 值: {value}");
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 开始写入寄存器: {address} 值: {value}");
                    }

                    // 处理位操作（如果有）
                    string processedValue = value;

                    // 确保值是十六进制格式（不带0x前缀）
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    // 发送写入命令
                    string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"1,{address},{processedValue},0\"";
                    adbService.ExecuteAdbCommandAsync(adbCommand, $"写操作 - 地址:{address} 值:{processedValue}");

                    // 等待命令执行
                    await Task.Delay(10);

                    // 验证写入是否成功 - 等待写入记录出现
                    var writeRecord = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Write", 500));

                    if (writeRecord != null && !string.IsNullOrEmpty(writeRecord.Values))
                    {
                        string actualValue = writeRecord.Values;
                        if (actualValue.StartsWith("0x"))
                        {
                            actualValue = actualValue.Substring(2);
                        }

                        // 比较写入的值是否匹配
                        bool success = string.Equals(actualValue, processedValue, StringComparison.OrdinalIgnoreCase);

                        if (success)
                        {
                            Console.WriteLine($"[ADBForm] 成功写入寄存器 {address} 值: {processedValue}");
                            return true;
                        }
                        else
                        {
                            Console.WriteLine($"[ADBForm] 写入寄存器 {address} 值不匹配，期望: {processedValue}，实际: {actualValue}");

                            // 如果不匹配且还有重试次数，则继续重试
                            if (retryCount < maxRetries)
                            {
                                retryCount++;
                                Console.WriteLine($"[ADBForm] 准备重试写入...");
                                continue; // 直接进入下一次循环，重新发送命令
                            }
                            else
                            {
                                Console.WriteLine($"[ADBForm] 写入寄存器 {address} 重试次数已用完，仍然不匹配");
                                return false;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 写入寄存器 {address} 失败，未找到写入确认记录");

                        // 如果未找到记录且还有重试次数，则重试
                        if (retryCount < maxRetries)
                        {
                            retryCount++;
                            Console.WriteLine($"[ADBForm] 准备重试写入...");
                            continue;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ADBForm] 写入寄存器 {address} 异常: {ex.Message}");

                    // 如果异常且还有重试次数，则重试
                    if (retryCount < maxRetries)
                    {
                        retryCount++;
                        Console.WriteLine($"[ADBForm] 准备重试写入...");
                        await Task.Delay(10); // 异常后稍作延迟再重试
                        continue;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            return false; // 理论上不会执行到这里
        }
    }
}
